'''
Created on Apr 6, 2012

@author: daoxuandung
'''
import logging
import json
from entity.entity import Event
from entity.entity import Location
from entity.entity import Ticket
from web import base
from web import urls
from web import util
from web.base import BaseHandler
from datetime import datetime, timedelta

class CreateHandler(BaseHandler):
    @base.user_required
    def post(self):
        """
        @param name: event name
        @param slogan: event slogan
        @param description: brief detail about event   
        """
        new_event = Event()
        new_event.organizer = util.get_current_user_key()
        new_event.name = self.request.params.get("name")
        new_event.slogan = self.request.params.get("slogan")
        new_event.description = self.request.params.get("description")
        new_event.end_time = datetime.now() + timedelta(days=2)
        new_event.put()
        
        # Return the id back to client
        self.response.write(json.dumps(util.ndb_to_dict(new_event)))

class ReadHandler(BaseHandler):
    def get(self):
        event_id = self.request.params.get('id')
        event = Event.get_by_id(int(event_id))
        if event:
            self.response.write(json.dumps(util.ndb_to_dict(event)))

class ReadListHandler(BaseHandler):
    def post(self):     
        size = int(self.request.params.get('limit'))
        event_list = Event.query().fetch_async(limit=size)
        event_list = event_list.get_result()
        return_list = []
        if event_list is not None and len(event_list) > 0:
            for e in event_list:
                return_list.append(util.ndb_to_dict(e))
            
        # Return the id back to client
        if return_list:
            self.response.write(json.dumps(return_list))

class UpdateHandler(BaseHandler):
    @base.user_required
    def post(self):
        updated = 1
        try:
            event_id = self.request.params.get("id")
            updatingEvent =  Event.get_by_id(int(event_id))
            updatingEvent.organizer = util.get_current_user_key()
            updatingEvent.name = self.request.params.get("name")
            updatingEvent.slogan = self.request.params.get("slogan")
            updatingEvent.description = self.request.params.get("description")
            tickets = json.loads(self.request.params.get("tickets"))
            logging.warn(tickets)
            # Not a good way of update since will create a new collection every time.
            # Need to revise to ticket_add + ticket_remove soon
            if (tickets):
                updatingEvent.tickets = []
                for ticket in tickets:
                    ticket = Ticket.get_by_id(int(ticket.get('id')))
                    updatingEvent.tickets.append(ticket.key)
                #logging.warn(json.dumps(updatingEvent.tickets))
            # Similar approach with locations
            locations = json.loads(self.request.params.get("locations"))
            if (locations):
                updatingEvent.locations_titles = []
                updatingEvent.locations = []
                for location in locations:
                    newLocation = Location()
                    #self.response.write(location)
                    newLocation.city = location.get('city')
                    newLocation.country = location.get('country')
                    newLocation.longitude = location.get('longitude')
                    newLocation.latitude = location.get('latitude')
                    newLocation.postal_code = location.get('postal_code')
                    newLocation.address = location.get('address')
                    newLocation.put()
                    updatingEvent.locations_titles.append(location.get('title'))
                    updatingEvent.locations.append(newLocation.key)
            updatingEvent.put()
            #self.response.write(json.dumps(locations))
        except Exception as e: 
            logging.warn("Exception: %s" %e)
            updated = 0
            
        # Return the id back to client
        self.response.write(updated)
        
    

class DeleteHandler(BaseHandler):
    def post(self):
        pass    
    

app = urls.app

def main():
    app.run()

if __name__ == '__main__':
    main()